import "./video.css"
import React, { useState, useEffect, useRef } from 'react'
import { getNextVideoApi } from "../../../api/home/video/getvideo/getVideo.ts"

function VideoPage() {
  const [videos, setVideos] = useState([{
    av: 'AV12345678',
    title: 'test',
    videoUrl: '/video.mp4',
    author: {
      nickname: '@catlover',
      avatar: 'https://example.com/avatar.jpg'
    },
    stats: {
      likes: 12345,
      comments: 2345,
      collects: 890,
      views: 1234567
    },
    createTime: '2023-08-20T10:00:00Z'
  }])
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isLoading, setIsLoading] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const containerRef = useRef(null)
  const mouseStartY = useRef(0)
  const mouseIsDown = useRef(false)
  const videoRefs = useRef([]);
  const hasRequest = useRef(false)

  // 初始化加载
  useEffect(() => {
    if(!hasRequest.current)
    {
      hasRequest.current=true
      loadInitialVideos()
    }
  }, [])

  useEffect(() => {
  videoRefs.current = videos.map((_, i) => videoRefs.current[i] || null);
  }, [videos]);

  const loadInitialVideos = async () => {
    setIsLoading(true)
    try {
      const initialVideos = await getNextVideoApi(-1)
      setVideos(prev => [...prev, ...initialVideos.items])
      setHasMore(initialVideos.has_more)
      console.log(videos)
    } finally {
      setIsLoading(false)
    }
  }

  // 鼠标事件处理
  const handleMouseDown = (e) => {
    const containerHeight = containerRef.current.clientHeight;
    const clickY = e.clientY - containerRef.current.getBoundingClientRect().top;

    if (clickY > (containerHeight - 40)) {
      return; // 阻止在进度条区域触发滑动
    }
    mouseIsDown.current = true
    mouseStartY.current = e.clientY
    containerRef.current.style.cursor = 'grabbing'

  }

  const handleMouseMove = (e) => {
    if (!mouseIsDown.current || !containerRef.current) return

    const deltaY = e.clientY - mouseStartY.current
    containerRef.current.style.transition = 'none'
    containerRef.current.style.transform = `translateY(calc(-${currentIndex * 100}vh + ${deltaY}px))`
  }

  const handleMouseUp = (e) => {
    mouseIsDown.current = false
    containerRef.current.style.cursor = 'grab'

    const deltaY = e.clientY - mouseStartY.current
    const absDeltaY = Math.abs(deltaY)

    if (absDeltaY < 20) {
      resetPosition()
      return
    }

    containerRef.current.style.transition = 'transform 0.5s cubic-bezier(0.22, 1, 0.36, 1)'
    handleSwipe(deltaY > 0 ? 'up' : 'down')
  }

  const resetPosition = () => {
    containerRef.current.style.transition = 'transform 0.3s ease'
    containerRef.current.style.transform = `translateY(-${currentIndex * 100}vh)`
  }

  const handleSwipe = (direction) => {
  setCurrentIndex(prev => {
    let newIndex = direction === 'down' ? prev + 1 : prev - 1;

    // 严格限制索引范围
    newIndex = Math.max(0, Math.min(newIndex, videos.length - 1));

    // 到达底部触发加载
    if (newIndex === videos.length - 1 && hasMore && !isLoading) {
      loadMoreVideos();
    }

    return newIndex;
  });
};

  // 加载更多视频
  // 修改加载更多逻辑
  const loadMoreVideos = async () => {
  if (isLoading || !hasMore) return;
  setIsLoading(true);

  try {
    const newVideos = await getNextVideoApi(
      videos[videos.length - 1]?.stats?.likes || 0
    );

    if (newVideos.items?.length > 0) {
      // 获取现有所有 av 号集合（使用 Set 提升查询性能）
      const existingAvs = new Set(videos.map(v => v.av));

      // 双重过滤：新视频内部去重 + 过滤已有视频
      const uniqueNewItems = newVideos.items.reduce((acc, item) => {
        // 检查是否已存在或当前批次已添加
        if (!existingAvs.has(item.av) && !acc.some(i => i.av === item.av)) {
          acc.push(item);
        }
        return acc;
      }, []);

      if (uniqueNewItems.length > 0) {
        setVideos(prev => {
          // 合并前再次验证（防止异步状态问题）
          const finalAvs = new Set(prev.map(v => v.av));
          const finalItems = uniqueNewItems.filter(item => !finalAvs.has(item.av));

          return [...prev, ...finalItems];
        });

        setHasMore(newVideos.has_more);

        // 同步更新 videoRefs（保持与视频列表长度一致）
        videoRefs.current = [
          ...videoRefs.current,
          ...Array(uniqueNewItems.length).fill(null)
        ];
      }
    }
  } finally {
    setIsLoading(false);
  }
};

  useEffect(() => {
  // 获取所有有效视频元素
  const allVideos = videoRefs.current
    .map(ref => ref?.video)
    .filter(Boolean);
  // 暂停所有视频
  allVideos.forEach(video => {
    video.pause()
    video.currentTime = 0
    video.pause()
  });

  // 播放当前视频
  const currentVideo = videoRefs.current[currentIndex]?.video;
  if (currentVideo) {
    currentVideo.play().catch(() => {
      // 处理自动播放阻止
    });
  }
}, [currentIndex]);

  // 格式化工具函数
  const formatNumber = (num) => {
    if (num > 10000) return `${(num/10000).toFixed(1)}w`
    if (num > 1000) return `${(num/1000).toFixed(1)}k`
    return num
  }

  const formatTime = (timeString) => {
    const date = new Date(timeString)
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`
  }

  return (
    <div
      className="video-container"
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      // onMouseLeave={handleMouseUp}
    >
      {/* 视频列表容器 */}
      <div
          className="video-list"
          ref={containerRef}
          style={{
            transform: `translateY(-${currentIndex * 100}vh)`,
            transition: 'transform 0.5s cubic-bezier(0.22, 1, 0.36, 1)'
          }}
      >
        {/* 视频项列表 */}
        {videos.map((video, index) => (
            <div
                key={video.av}
                className="video-item"
                style={{
                  transform: `translateY(${index * 100}vh)`,
                  zIndex: index === currentIndex ? 2 : 1
                }}
            >


              {/* 视频播放器 */}
              <div className="video-player">
                <video
                    ref={(el) => videoRefs.current[index] = { video: el }}
                    autoPlay={index === currentIndex}
                    muted
                    controls={true}
                    loop
                    playsInline
                    style={{
                      opacity: index === currentIndex ? 1 : 0.5,
                      transition: 'opacity 0.3s ease',
                      transform: `scale(${index === currentIndex ? 1 : 0.95})`
                    }}
                    preload={Math.abs(index - currentIndex) <= 1 ? "auto" : "none"}
                    // preload='metadata'
                >
                  <source src={video.videoUrl} type="video/mp4"/>
                </video>
              </div>

              {/* 视频元信息 */}
              <div className="video-meta">
                <div className="av-id">{video.av}</div>
                <h2 className="video-title">{video.title}</h2>
              </div>

              {/* 用户信息 */}
              <div className="user-info">
                <img
                    src={video.author.avatar}
                    alt="avatar"
                    className="user-avatar"
                />
                <div className="user-details">
                  <div className="username">{video.author.nickname}</div>
                  <div className="video-stats">
                    <span>{formatNumber(video.stats.views)}次播放</span>
                    <span>•</span>
                    <span>{formatTime(video.createTime)}</span>
                  </div>
                </div>
              </div>

              {/* 操作栏 */}
              <div className="action-bar">
                <div className="action-button">
                  {/*点赞*/}
                  <span className="count">{formatNumber(video.stats.likes)}</span>
                </div>
                <div className="action-button">
                  {/*评论*/}
                  <span className="count">{formatNumber(video.stats.comments)}</span>
                </div>
                <div className="action-button">
                  {/*收藏*/}
                  <span className="count">{formatNumber(video.stats.collects)}</span>
                </div>
              </div>
            </div>
        ))}
      </div>

      {/* 加载指示器 */}
      {isLoading && (
          <div className="loading-indicator">
            <div className="loading-spinner"/>
          </div>
      )}
    </div>
  )
}

export default VideoPage